package com.csmall.order.webapi.service.Impl;

import com.csmall.cart.service.CartService;
import com.csmall.commons.pojo.order.dto.OrderAddDTO;
import com.csmall.commons.pojo.order.entity.Order;
import com.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import com.csmall.commons.restful.JsonPage;
import com.csmall.order.service.OrderService;
import com.csmall.order.webapi.mapper.OrderMapper;
import com.csmall.stock.service.StockService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Name: OrderServiceImpl
 * @Author: 西风残叶
 * @Date: 2024/8/18 18:34
 * @Version: 1.0
 * @TODO: TODO
 */
@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    // 应用远程服务消费远程消费者
    @DubboReference
    private StockService stockService;
    @DubboReference
    private CartService cartService;

    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 1. 减少库存数
        StockReduceCountDTO countDTO = new StockReduceCountDTO();
        countDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        countDTO.setReduceCount(orderAddDTO.getCount());
        // 利用Dubbo调用远程服务
        stockService.reduceStockCount(countDTO);
        // 2. 删除购物车中的对应商品
        cartService.deleteUserCart(orderAddDTO.getUserId(),
                orderAddDTO.getCommodityCode());
        // 3. 新增订单
        Order order = new Order();
        BeanUtils.copyProperties(orderAddDTO, order);
        // 执行新增
        orderMapper.insertOrder(order);
        log.info("新增订单信息为:{}", order);
    }

    /**
     * 按页获取所有订单
     * 此方法实现分页查询功能，通过指定的页码和页面大小来返回相应的订单信息
     *
     * @param page     当前页码
     * @param pageSize 每页显示的记录数
     * @return 返回一个PageInfo对象，包含当前页的订单列表以及分页相关信息
     */
    public JsonPage<Order> getAllOrdersByPage(Integer page, Integer pageSize){
        // 确定分页状态(分页设置:第几页,每页几条)
        PageHelper.startPage(page, pageSize);
        // 查询数据列表,会根据分页设置进行限制(在SQL语句末尾添加limit关键字)
        List<Order> list = orderMapper.findAllOrders();
        // 返回分页信息和查询结果

        return JsonPage.restPage(new PageInfo<>(list));
    }
}